package com.ns.main.run;

import java.util.List;
import java.util.concurrent.BlockingQueue;

import com.ns.main.bean.CrawlRule;
import com.ns.main.service.CrawlService;
import com.ns.main.util.CrawlerUtil;

public class BookURLProducter implements Runnable {

	private BlockingQueue<String> urlqueue;
	private CrawlService service;
	private boolean flag = true;
	private int total = 4;

	public void stop() {
		flag = false;
	}

	public BookURLProducter(BlockingQueue queue) {
		this.urlqueue = queue;
		service = new CrawlService();
		System.out.println("Producter on line ... ");
	}

	@Override
	public void run() {
		System.out.println("Producter : "+Thread.currentThread().getName());
		while (flag) {
			CrawlRule rule = new CrawlRule();
			rule.setSelectorType(CrawlerUtil.CLASS);
			rule.setSelector("grid");
			List<String> urls = null;
			for (int i = 1; i < total; i++) {
				rule.setUrl("http://book.58xs.com/quanben/0/" + i + ".html");
				urls = service.getBookURL(rule);
				System.out.println(rule.getUrl() + " " + urls.size());
				if (null == urls || urls.size() <= 0) {
					flag = false;
				} else {
					for (String u : urls) {
						try {
							 urlqueue.put(u);
						} catch (Exception e) {
							e.printStackTrace();
							System.out.println("Failed to put...");
						}
					}
				}
				if (i == total - 1) {
					flag = false;
				}
			}

		}
	}

}
